package com.zxcz.tools;

import java.util.ArrayList;
import java.util.Arrays;

import com.google.common.base.Joiner;

/**
 * 构建redis key工具类
 */
public class RedisKeyBuilder {
	//默认值
	private static final String KEY_PREFIX = "smartpen";
	private static final String KEY_SPLIT_CHAR =":";
	
	private String keyPrefix;//前缀
	private String keySplitChar;//分隔符
	private ArrayList<String> keys;//key列表
	
	public RedisKeyBuilder() {
		this(KEY_PREFIX,KEY_SPLIT_CHAR);
	}
	
	public RedisKeyBuilder(String keyPrefix, String keySplitChar) {
		this.keyPrefix = keyPrefix;
		this.keySplitChar = keySplitChar;
		this.keys = new ArrayList<>();
		keys.add(this.keyPrefix);
	}
	
	/**
     * 添加子键名
     * @param part 子键名
     * @return 当前对象
     */
	public RedisKeyBuilder append(String part) {
		this.keys.add(part);
		return this;
	}
	
	/**
     * 添加子键名列表
     * @param parts 子键名列表
     * @return 当前对象
     */
	public RedisKeyBuilder append(String[] parts) {
		this.keys.addAll(Arrays.asList(parts));
		return this;
	}
	
	/**
     * 拼接键名
     * @return 拼接后的键名
     */
	public String build() {
		return Joiner.on(keySplitChar).skipNulls().join(keys);
	}
	
	/**
     * 快速拼接键名
     * @param keys 子键名列表
     * @return 拼接后的键名
     */
	public static String generate(String[] keys) {
		return new RedisKeyBuilder().append(keys).build();
	}
}
